package controller

import (
	"coursedesign/projectGo/common"
	"coursedesign/projectGo/model"
	"coursedesign/projectGo/response"
	"fmt"
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
	"strconv"
)

type ICompanyController interface {
	RestController
}

type CompanyController struct {
	DB *gorm.DB
}

func NewCompanyController() ICompanyController {
	db := common.GetDB()
	return CompanyController{DB: db}
}

func (c2 CompanyController) Create(c *gin.Context) { // 创建货代公司
	var requestCompany model.Company
	c.ShouldBindJSON(&requestCompany)
	if requestCompany.ID == "" {
		response.Fail(c, "公司工商注册号不可为空", nil)
		return
	}

	result := c2.DB.Find(&requestCompany).RowsAffected
	if result != 0 {
		response.Fail(c, "公司已存在", nil)
		return
	}
	err := c2.DB.Create(&requestCompany).Error
	if err != nil {
		response.Fail(c, err.Error(), nil)
		return
	}

	response.Success(c, gin.H{"store": requestCompany}, "创建成功")
}

func (c2 CompanyController) Update(c *gin.Context) { // 更新信息
	// 绑定body中参数（更新后的值）
	var requestCompany model.Company
	c.ShouldBindJSON(&requestCompany)
	fmt.Println(requestCompany)
	if requestCompany.ID == "" {
		response.Fail(c, "工商注册号不可为空", nil)
		return
	}
	result := c2.DB.Where(&requestCompany).First(&model.Company{}).RowsAffected
	if result != 0 {
		response.Fail(c, "公司已存在", nil)
		return
	}

	// 更新
	err := c2.DB.Model(&model.Company{}).Where("id=?", c.Params.ByName("id")).Updates(&requestCompany).Error
	if err != nil {
		response.Fail(c, err.Error(), nil)
		return
	}
	response.Success(c, gin.H{"store": requestCompany}, "修改成功")
}

func (c2 CompanyController) PageList(c *gin.Context) { // 分页给数据
	id, _ := c.GetQuery("id")
	if id != "" {
		var selectCompany model.Company

		// 查询
		err := c2.DB.Model(&selectCompany).Where("id=?", id).First(&selectCompany).Error
		if err != nil {
			response.Fail(c, err.Error(), nil)
			return
		}
		response.Success(c, gin.H{"company": selectCompany}, "查询成功")
		return
	}
	// 获取分页参数
	tempNum, _ := c.GetQuery("pagenum")
	tempSize, _ := c.GetQuery("pagesize")
	pageNum, _ := strconv.Atoi(tempNum)   // 当前页数
	pageSize, _ := strconv.Atoi(tempSize) // 页内个数
	if pageNum == 0 {
		pageNum = 1
	}
	if pageSize == 0 {
		pageSize = 10
	}
	// 分页
	var companies []model.Company
	c2.DB.Order("id").Offset((pageNum - 1) * pageSize).Limit(pageSize).Find(&companies)

	// 前端渲染分页也要知道总数
	var total int64
	c2.DB.Model(model.Company{}).Count(&total)

	response.Success(c, gin.H{"data": companies, "total": total}, "查询成功")
}

func (c2 CompanyController) Delete(c *gin.Context) {
	// 获取path中的参数（仓库号）
	// storeId, _ := strconv.Atoi(c.Params.ByName("id")) // 强制转换为数字
	var deleteCompany model.Company

	// 查询
	err := c2.DB.Model(&deleteCompany).Where("id=?", c.Params.ByName("id")).Delete(&deleteCompany).Error
	if err != nil {
		response.Fail(c, err.Error(), nil)
		return
	}
	response.Success(c, nil, "删除成功")
}
